package com.gupaoedu.chat.server.handler;

import com.gupaoedu.chat.processor.MsgProcessor;
import com.gupaoedu.chat.protocol.IMMessage;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.concurrent.EventExecutorGroup;

/**
 * Created by ASUS on 2017/10/21.
 */
public class ScoketHandler extends SimpleChannelInboundHandler<IMMessage> {

    private MsgProcessor processor = new MsgProcessor();
    //离线了
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
        System.out.println("ScoketHandler channelInactive ..");
    }

    //发生异常了
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
        System.out.println("ScoketHandler exceptionCaught ..");
    }

    //加入进来 服务端handler创建
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        super.handlerAdded(ctx);
        System.out.println("ScoketHandler handlerAdded ..");
    }

    /**
     * 服务端Handler移除
     * 需要将其登出
     */
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        super.handlerRemoved(ctx);
        processor.logout(ctx.channel(),true);
        System.out.println("ScoketHandler handlerRemoved ..");
    }

    /**
     * 后台通信中的通道读取数据
     */
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, IMMessage imMessage) throws Exception {
        System.out.println("ScoketHandler channelRead0 ..");
        processor.sendMsg(channelHandlerContext.channel(),imMessage,true);
    }


    //tcp链路建立成功后调用
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("ScoketHandler channelActive ..");
    }
}
